<?php

declare(strict_types=1);

namespace app\controller\v1;


use think\Request;
use think\Response;
use think\exception\ValidateException;
use app\service\UserService;
use app\model\User;
use app\service\MiniProgramService;

/**
 * 用户控制器
 * 处理用户信息管理相关功能
 */
class UserController extends BaseAPIController
{

    /**
     * 获取用户信息
     *
     * @return Response
     */
    public function info()
    {
        try {
            $user = UserService::getCurrentUser();
            // if (!$user) {
            //     return $this->error('用户未登录', 401);
            // }

            // // 获取完整的用户信息
            // $fullUserInfo = $this->userService->getUserInfo($user['user_id']);

            return $this->success($user, '获取成功');
        } catch (\Exception $e) {
            trace('获取用户信息失败: ' . $e->getMessage(), 'error');
            return $this->error('获取用户信息失败', 500);
        }
    }


    public function getUserDetail()
    {
        try {
            $userDetail = $this->userService->getUserDetail($this->userService->getCurrentUserId());
            return $this->success($userDetail, '获取成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400);
        }
    }


    /**
     * 获取用户地址
     */
    public function getUserAddress(Request $request)
    {
        $user = UserService::getCurrentUser();
        $address = $this->userService->getUserAddress((int)$user['user_id'], $user['address_id'], $this->request->get(''));
        return $this->success($address, '获取成功');
    }

    // 保存用户添加的地址
    public function saveUserAddress(Request $request)
    {
        try {
            $user = UserService::getCurrentUser();
            $address = $this->userService->saveUserAddress((int)$user['user_id'], $user['address_id'], $request->param());
            return $this->success($address, '保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400);
        }
    }

    // 获取地址信息
    public function getAddressInfo(Request $request)
    {
        $id = $request->param('id');
        if (!$id) {
            return $this->error('参数错误', 400);
        }
        $address = $this->userService->getAddressInfo((int)$id);
        return $this->success($address, '获取成功');
    }

    /**
     * 更新用户信息
     *
     * @param Request $request
     * @return Response
     */
    public function update(Request $request)
    {
        try {
            $userId = UserService::getCurrentUserId();
            if (!$userId) {
                return $this->error('用户未登录', 401);
            }

            $params = $request->param();

            // 更新用户信息
            $result = $this->userService->updateUserInfo($userId, $params);

            if ($result) {
                // 获取更新后的用户信息
                $updatedUser = $this->userService->getUserInfo($userId);
                return $this->success($updatedUser, '更新成功');
            } else {
                return $this->error('更新失败', 500);
            }
        } catch (ValidateException $e) {
            return $this->error($e->getMessage(), 400);
        } catch (\Exception $e) {
            trace('更新用户信息失败: ' . $e->getMessage(), 'error');
            return $this->error('更新失败，请重试', 500);
        }
    }

    /**
     * 上传头像
     *
     * @param Request $request
     * @return Response
     */
    public function uploadAvatar(Request $request)
    {
        try {
            $userId = UserService::getCurrentUserId();
            if (!$userId) {
                return $this->error('用户未登录', 401);
            }

            $file = $request->file('avatar');
            if (!$file) {
                return $this->error('请选择要上传的头像', 400);
            }

            // 验证文件类型
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
            $extension = strtolower($file->getOriginalExtension());
            if (!in_array($extension, $allowedTypes)) {
                return $this->error('只支持jpg、jpeg、png、gif格式的图片', 400);
            }

            // 验证文件大小 (2MB)
            if ($file->getSize() > 2 * 1024 * 1024) {
                return $this->error('头像文件大小不能超过2MB', 400);
            }

            // 保存文件
            $saveName = \think\facade\Filesystem::disk('public')->putFile('avatar', $file);
            if (!$saveName) {
                return $this->error('头像上传失败', 500);
            }

            // 构建完整的URL
            $avatarUrl = '/storage/' . $saveName;

            // 更新用户头像
            $result = $this->userService->updateUserInfo($userId, ['avatar' => $avatarUrl]);

            if ($result) {
                return $this->success(['avatar' => $avatarUrl], '头像上传成功');
            } else {
                return $this->error('头像更新失败', 500);
            }
        } catch (\Exception $e) {
            trace('头像上传失败: ' . $e->getMessage(), 'error');
            return $this->error('头像上传失败', 500);
        }
    }

    /**
     * 获取用户列表（管理员功能）
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        try {
            // 检查管理员权限
            if (!UserService::isAdmin()) {
                return $this->error('权限不足', 403);
            }

            $params = $request->param();
            $result = User::searchUsers($params);

            return $this->success($result, '获取成功');
        } catch (\Exception $e) {
            trace('获取用户列表失败: ' . $e->getMessage(), 'error');
            return $this->error('获取用户列表失败', 500);
        }
    }

    /**
     * 获取指定用户信息（管理员功能）
     *
     * @param int $id
     * @return Response
     */
    public function read(int $id)
    {
        try {
            // 检查权限：管理员或本人
            $currentUserId = UserService::getCurrentUserId();
            if (!UserService::isAdmin() && $currentUserId !== $id) {
                return $this->error('权限不足', 403);
            }

            $user = $this->userService->getUserInfo($id);
            if (!$user) {
                return $this->error('用户不存在', 404);
            }

            return $this->success($user, '获取成功');
        } catch (\Exception $e) {
            trace('获取用户信息失败: ' . $e->getMessage(), 'error');
            return $this->error('获取用户信息失败', 500);
        }
    }

    /**
     * 禁用/启用用户（管理员功能）
     *
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function toggleStatus(Request $request, int $id)
    {
        try {
            // 检查管理员权限
            if (!UserService::isAdmin()) {
                return $this->error('权限不足', 403);
            }

            $user = User::find($id);
            if (!$user) {
                return $this->error('用户不存在', 404);
            }

            // 不能禁用自己
            if ($id === UserService::getCurrentUserId()) {
                return $this->error('不能禁用自己', 400);
            }

            $status = $request->param('status', $user->status == 1 ? 0 : 1);
            $user->status = $status;
            $result = $user->save();

            if ($result) {
                $statusText = $status == 1 ? '启用' : '禁用';
                return $this->success([], "用户{$statusText}成功");
            } else {
                return $this->error('操作失败', 500);
            }
        } catch (\Exception $e) {
            trace('切换用户状态失败: ' . $e->getMessage(), 'error');
            return $this->error('操作失败', 500);
        }
    }

    /**
     * 重置用户密码（管理员功能）
     *
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function resetPassword(Request $request, int $id)
    {
        try {
            // 检查管理员权限
            if (!UserService::isAdmin()) {
                return $this->error('权限不足', 403);
            }

            $user = User::find($id);
            if (!$user) {
                return $this->error('用户不存在', 404);
            }

            $newPassword = $request->param('password', '123456'); // 默认密码
            $user->password = $newPassword; // 会自动加密
            $result = $user->save();

            if ($result) {
                return $this->success([], '密码重置成功');
            } else {
                return $this->error('密码重置失败', 500);
            }
        } catch (\Exception $e) {
            trace('重置密码失败: ' . $e->getMessage(), 'error');
            return $this->error('密码重置失败', 500);
        }
    }


    //我的足迹

    public function getMyFootprint(Request $request)
    {
        try {
            $result = $this->userService->getMyFootprint($request);
            return $this->success($result);
        } catch (\Exception $e) {
            trace('获取我的足迹失败: ' . $e->getMessage(), 'error');
            return $this->error('获取我的足迹失败', 400);
        }
    }


    // 获取店铺收藏
    public function getMyCollectionShop(Request $request)
    {
        try {
            $result = $this->userService->getMyCollectionShop($request);
            return $this->success($result);
        } catch (\Exception $e) {
            trace('获取我的收藏失败: ' . $e->getMessage(), 'error');
            return $this->error('获取我的收藏失败', 400);
        }
    }

    //商品收藏
    public function getMyCollectionGoods(Request $request)
    {
        try {
            $result = $this->userService->getMyCollectionGoods($request);
            return $this->success($result);
        } catch (\Exception $e) {
            trace('获取我的收藏失败: ' . $e->getMessage(), 'error');
            return $this->error('获取我的收藏失败', 400);
        }
    }

    //获取用户小程序码
    public function getUserMiniQrcode(Request $request)
    {
        $uid = $this->userService->getCurrentUserId();
        if (file_exists(root_path() . 'public/upload/avatar/'.md5('meo-'.$uid).'.png')) {
            return $this->success(env('APP_URL') . '/upload/avatar/'.md5('meo-'.$uid).'.png');
        }
       $miniQrcode = (new MiniProgramService())->getMiniQrcode([
            'scene' => 'uid='.$uid,
            'page' =>'pages/index/index',
            'width' => 150,
            'check_path' => false,
        ],'upload/avatar',md5('meo'.$uid).'.png');
        $miniQrcode = env('APP_URL') . $miniQrcode;
        return $this->success($miniQrcode);
    }

}
